package com.ygqh.baby.service.task;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.CommentType;
import com.ygqh.baby.ao.WxMessageType;
import com.ygqh.baby.model.wdt.qyb.PushOrderErrorInfo;
import com.ygqh.baby.model.wdt.qyb.WdtQybResult;
import com.ygqh.baby.po.AdminPurchase;
import com.ygqh.baby.service.YgOrderLogService;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.utils.MailUtil;

@Component
public class YgAsynClient implements YgAsynCallBack {
	protected final Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private YgOrderService orderService;
	@Autowired
	private YgOrderLogService ygOrderLogService;
	@Autowired
	private YgAsynServer server;
	@Autowired
	private MailUtil mailUtil;
	@Value("${mail.to.all}")
	private String mailToAll;
	@Value("${mail.to.kefu}")
	protected String mailToKeFu;

	/**
	 * 异步 同步订单到旺店通
	 * 
	 * @param orderIds
	 */
	public void syncOrder(final List<Long> orderIds) {
		logger.debug("客户端：接收到需要同步的订单id：" + orderIds.toString());
		new Thread(() -> server.syncOrder(YgAsynClient.this, orderIds)).start();
		logger.debug("客户端：异步调用同步订单成功");
	}

	public void syncQybOrder(final List<Long> orderIds) {
		logger.debug("客户端：接收到需要同步的订单id：" + orderIds.toString());
		new Thread(() -> server.syncQybOrder(YgAsynClient.this, orderIds)).start();
		logger.debug("客户端：异步调用同步订单成功");
	}

	/**
	 * 异步发送微信消息，及短信（暂时作废）
	 * 
	 * @param orderIds
	 * @param msgType
	 */
	public void sendWxMsg(List<Long> orderIds, WxMessageType msgType) {
		logger.debug("客户端：接收到需要发送微信模板消息的订单id：" + orderIds.toString());
		new Thread(() -> server.sendWxMsg(YgAsynClient.this, orderIds, msgType)).start();
		logger.debug("客户端：异步发送微信模板消息成功");
	}

	/**
	 * 异步发送新赞、评论的消息
	 * 
	 * @param publishId
	 * @param userId
	 * @param nickName
	 * @param commentType
	 */
	public void sendNewReviewMsg(Long publishId, Long userId, String nickName, CommentType commentType) {
		new Thread(() -> server.sendNewReviewMsg(YgAsynClient.this, publishId, userId, nickName, commentType)).start();
	}

	/**
	 * 异步发送邀请注册成功的消息
	 * 
	 * @param orderIds
	 * @param msgType
	 */
	public void sendInviteRegisterSuccessMsg(String operId, String inviterSourceCode, String registerUserName,
			String registerNickName) {
		new Thread(() -> server.sendInviteRegisterSuccessMsg(YgAsynClient.this, operId, inviterSourceCode, registerUserName,
				registerNickName)).start();
	}

	/**
	 * 异步同步进货单到旺店通
	 * 
	 * @param purchaseOrder
	 */
	public void syncPurchaseOrder(final AdminPurchase purchaseOrder) {
		logger.debug("客户端：接收到需要同步的进货单id：" + purchaseOrder.toString());
		new Thread(() -> server.syncPurchaseOrder(YgAsynClient.this, purchaseOrder)).start();
		logger.debug("客户端：异步调用同步进货单成功");
	}

	/**
	 * 异步同步进货单到旺店通
	 * 
	 * @param purchaseOrder
	 */
	public void syncQybPurchaseOrder(final AdminPurchase purchaseOrder) {
		logger.debug("客户端：接收到需要同步的进货单id：" + purchaseOrder.toString());
		new Thread(() -> server.syncQybPurchaseOrder(YgAsynClient.this, purchaseOrder)).start();
		logger.debug("客户端：异步调用同步进货单成功");
	}

	/**
	 * 异步同步进货单到旺店通
	 * 
	 * @param orderStatus
	 * @param autoAudit
	 * 
	 * @param orderStatus
	 * 
	 * @param purchaseOrder
	 */
	public void applyRefundOrder(final String returnCode, Boolean isSend) {
		new Thread(() -> {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			server.applyRefundOrder(YgAsynClient.this, returnCode, isSend);
		}).start();
	}

	@Override
	public void syncPurchaseOrderCallBack(Boolean falg) {
		System.out.println("客户端：进货单同步，服务端回调状态为：" + falg);
		logger.debug("客户端：进货单同步，服务端发送微信消息，回调状态为：" + falg);

	}

	@Override
	public void sendWxMsgCallBack(Boolean falg) {
		System.out.println("客户端：服务端回调状态为：" + falg);
		logger.debug("客户端：服务端发送微信消息，回调状态为：" + falg);

	}

	/**
	 * 异步发送申请提现邮件
	 * 
	 * @param commissionCode
	 */
	public void syncCommissionDetail(String commissionCode) {
		logger.debug("客户端：接收到需要同步的申请提现：" + commissionCode);
		new Thread(() -> server.syncCommissionDetail(YgAsynClient.this, commissionCode)).start();
		logger.debug("客户端：异步调用同步申请提现单成功");
	}

	@Override
	public void syncCommissionDetailCallBack(Boolean falg) {
		System.out.println("客户端：服务端回调状态为：" + falg);
		logger.debug("客户端：服务端发送微信消息，回调状态为：" + falg);
	}

	public void applyRefundOrderBack(boolean falg) {
		System.out.println("applyRefundOrderBack 服务端回调状态为：" + falg);

	}

	@Override
	public void syncOrderCallBack(List<PushOrderErrorInfo> errorList) {

		if (!CollectionUtils.isEmpty(errorList)) {
			logger.info(errorList.toString());
			sendMail(errorList, "guohao@yiigoo.com", mailUtil, "同步订单");
		}
	}

	public void applyRefundOrderBack(WdtQybResult applyRefundResult, WdtQybResult pushChangeResult, String error,
			String returnCode) {
		String msg = returnCode + "%s";
		Boolean isSend = false;

		if (applyRefundResult == null || applyRefundResult.getCode() != 0) {
			msg = String.format(msg, " 申请退款失败。" + error + ";%s");
			isSend = true;
		}

		if (pushChangeResult == null || pushChangeResult.getCode() != 0) {
			msg = String.format(msg, " 推送售前退换订单失败。" + error);
			isSend = true;
		}

		if (!StringUtil.isBlank(error)) {
			isSend = true;
			msg = error;
		}
		if (isSend) {
			List<PushOrderErrorInfo> errorList = new ArrayList<PushOrderErrorInfo>();
			PushOrderErrorInfo errorInfo = new PushOrderErrorInfo(returnCode, msg.replace("%s", ""));
			errorList.add(errorInfo);
			sendMail(errorList, "guohao@yiigoo.com", mailUtil, "申请退款");
		}
	}
}
